#include "Mux.hh"

using namespace std;

Mux::Mux(){
};
Mux::Mux(const char* filename, Settings* setting){
  SetFile( filename );
  fSett = setting;
  fVerbose = fSett->VLevel();
  cout << "verbose level " << fVerbose << endl;
  ReadMux();
  if(fVerbose>0){
    PrintMux();
  }
};
Mux::~Mux(){
  cout << "destructor" << endl;
};
void Mux::ReadMux(){
  TEnv *config = new TEnv(fInputFile.data());
  if(fVerbose>1)
    cout << "reading cd" << endl;

  fCDPosFWHM = config->GetValue("CD.FWHM.pos",0.);
  for(int quadr=0; quadr<4; quadr++){
    for(int strip=0; strip<16; strip++){
      fCDRingPos[quadr][strip] = config->GetValue(Form("CD.Quadrant%d.ring.%d.pos",quadr,strip),0.);
      fCDStripPos[quadr][strip] = config->GetValue(Form("CD.Quadrant%d.strip.%d.pos",quadr,strip),0.);
    }
  }
  delete config;
}
void Mux::PrintMux(){
  cout << "CD Mux" << endl;
  cout << "CD.FWHM.pos\t" << fCDPosFWHM << endl;
  for(int quadr=0; quadr<4; quadr++){
    for(int strip=0; strip<16; strip++){
      cout << Form("CD.Quadrant%d.ring.%d.pos\t",quadr,strip) << fCDRingPos[quadr][strip] <<endl;
      cout << Form("CD.Quadrant%d.strip.%d.pos\t",quadr,strip) << fCDStripPos[quadr][strip] <<endl;
    }
  }
};
int Mux::StripNr(unsigned short id, int quadr, bool strip){
  int res = -1;
  if(quadr <0 || quadr >3){
    cerr << "quadrant number out of range, is " << quadr << " (range 0-3)" << endl;
    return -4;
  }
  if(strip){
    while( id > fCDStripPos[quadr][res+1]-3*fCDPosFWHM){
      res++;
      //cout << "res " << res << endl;
      if(res==15)
	break;
    }
    if(res==15){ // res=15 everything bigger than 14, check if its 15 or junk
      if(id > fCDStripPos[quadr][res]+3*fCDPosFWHM)
	res++;
    }
    if( (res<0) || (res>15) ){
      if(fSett->VLevel()>2)
	cerr << "error res = " << res << " id = " << id << endl; 
      return res;
    }
    else{
      if(id > fCDStripPos[quadr][res]+3*fCDPosFWHM)
	return -3;
    }
  }
  else{
    while( id > fCDRingPos[quadr][res+1]-3*fCDPosFWHM){
      res++;
      //cout << "res " << res << endl;
      if(res==15)
	break;
    }
    if(res==15){ // res=15 everything bigger than 14, check if its 15 or junk
      if(id > fCDRingPos[quadr][res]+3*fCDPosFWHM)
	res++;
    }
    if( (res<0) || (res>15) ){
      if(fSett->VLevel()>2)
	cerr << "error res = " << res << " id = " << id << endl; 
      return res;
    }
    else{
      if(id > fCDRingPos[quadr][res]+3*fCDPosFWHM)
	return -3;
    }
  }
  return res;
}
